package com.example.design.pattern.structure.component;

public class CompositePatternDemo {

    public static void main(String[] args) {
        Composite composite = new Composite("/");
        Leaf leaf1 = new Leaf("叶子1");
        composite.add(leaf1);
        Leaf leaf2 = new Leaf("叶子2");
        composite.add(leaf2);
        Leaf leaf3 = new Leaf("叶子3");
        composite.add(leaf3);
        Leaf leaf4 = new Leaf("叶子4");
        composite.add(leaf4);
        
        Composite composite2 = new Composite("/user");
        Leaf leaf21 = new Leaf("叶子21");
        composite2.add(leaf21);
        Leaf leaf22 = new Leaf("叶子22");
        composite2.add(leaf22);
        
        composite.add(composite2);
        
        Leaf leaf5 = new Leaf("叶子5");
        composite.add(leaf5);
        
        print(composite);
    }
    
    public static void print(Component component) {
        if (component instanceof Leaf) {
            component.operation();
        }
        
        if (component instanceof Composite) {
            Composite c = (Composite) component;
            for (Component com : c.getComponents()) {
                print(com);
            }
        }
    }
}
